
package com.ruoyi.client.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.mapper.OrderItemMapper;
import com.ruoyi.client.mapper.OrderMapper;
import com.ruoyi.client.pojo.form.OrderInsertForm;
import com.ruoyi.client.pojo.form.OrderItemInsertForm;
import com.ruoyi.client.pojo.form.OrderQueryPageForm;
import com.ruoyi.client.pojo.vo.OrderDetailVo;
import com.ruoyi.client.pojo.vo.OrderItemVo;
import com.ruoyi.client.pojo.vo.OrderVo;
import com.ruoyi.client.service.OrderService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.myshop.domain.Order;
import com.ruoyi.myshop.domain.OrderItem;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


@Service("ClientOrderServiceImpl")
public class OrderServiceImpl implements OrderService {

    @Resource(name = "ClientOrderMapper") //注入指定命名的Bean
    private OrderMapper orderMapper;
    @Resource(name = "ClientOrderItemMapper") //注入指定命名的Bean
    private OrderItemMapper orderItemMapper;


    /**
     * 增加订单（从商品列表创建）
     */
    @Override
    @Transactional
    public Long insert(OrderInsertForm form) {
        // 获取用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        List<OrderItemInsertForm> orderItemList = form.getGoodsList();

        //计算总金额
        double amount = 0.0;
        for (OrderItemInsertForm item : orderItemList) {
            amount += item.getCount() * item.getPrice().doubleValue();
        }

        //保存订单
        Order order = new Order();
        order.setUserId(userId); //订单是我的
        order.setAmount(new BigDecimal(amount)); //设置总金额
        order.setNote(form.getNote());
        //生成订单,如果出错，抛出异常
        if (orderMapper.insert(order) <= 0) {
            throw new ServiceException("生成订单数据库错误");
        }

        //获取订单id
        //OrderMapper.xml文件insert方法中使用useGeneratedKeys 此时order.id可以生成返回
        //useGeneratedKeys="true" keyProperty="id"
        Long orderId = order.getId();

        //生成订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (OrderItemInsertForm item : orderItemList) {
            OrderItem orderItem = new OrderItem();
            //使用BeanUtil工具类将cartItemVo中的属性复制到orderItem对象中
            BeanUtils.copyProperties(item, orderItem);//属性变量命名、数据类型要相同
            orderItem.setOrderId(orderId);
            orderItems.add(orderItem);
        }
        //批量insert订单项数据,返回结果orderId
        return orderItemMapper.insertBatch(orderItems) > 0 ? orderId : null;
    }

    /**
     * 更改订单信息
     */
    @Override
    @Transactional
    public Boolean update(Order order) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        return orderMapper.update(order) > 0;
    }

    /**
     * 更改订单状态( 0初始  1取消 2完成)
     */
    @Override
    public Boolean updateStatus(Long orderId, Integer status) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);  //订单状态
        return orderMapper.update(order) > 0;
    }

    /**
     * 查询订单详情By订单Id
     */
    @Override
    public OrderDetailVo selectDetailById(Long orderId) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        //查询订单是否存在
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new ServiceException("id对应的订单不存在");
        }

        OrderDetailVo orderDetailVo = new OrderDetailVo();
        BeanUtils.copyProperties(order, orderDetailVo);

        List<OrderItemVo> orderItemVoList = orderItemMapper.selectVoListByOrderId(orderId);
        orderDetailVo.setOrderItemList(orderItemVoList);
        return orderDetailVo;
    }

    /**
     * 查询我的订单明细列表(有商品项)
     */
    @Override
    public List<OrderDetailVo> selectMyList(OrderQueryPageForm form)
    {
        // 获取用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        //form有 pageNum、pageSize、status
        Order order = new Order();
        order.setStatus(form.getStatus()); //订单状态
        order.setUserId(userId); //我的订单

        List<OrderDetailVo> orderDetailVoList =orderMapper.selectVoMyList(order);
        // 为每个订单查询订单商品项
        for (OrderDetailVo orderDetailVo : orderDetailVoList) {
            List<OrderItemVo> orderItemVoList = orderItemMapper.selectVoListByOrderId(orderDetailVo.getId());
            orderDetailVo.setOrderItemList(orderItemVoList);
        }
        return orderDetailVoList;
    }
}
